/*
 * @Author: 李无敌
 * @Date: 2025-07-25 17:03:54
 * @LastEditors: 李无敌
 * @LastEditTime: 2025-08-13 14:56:11
 * @FilePath: \nest-base\src\common\filters\http-exception.filter.ts
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';
import { ResponseCode, getCodeMessage } from '../types/response-code.enum';
import { createErrorResponse } from '../types/response.types';
import { getResponseCodeFromHttpStatus } from '../interceptors/response.interceptor';

/**
 * HTTP异常过滤器
 * 统一处理HTTP异常并返回标准格式的错误响应
 */
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();
    const request = ctx.getRequest<FastifyRequest>();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();

    // 获取自定义状态码
    const responseCode = getResponseCodeFromHttpStatus(status);
    
    // 获取错误消息
    let message: string;
    if (typeof exceptionResponse === 'string') {
      message = exceptionResponse;
    } else if (typeof exceptionResponse === 'object' && 'message' in exceptionResponse) {
      const msg = exceptionResponse.message;
      if (Array.isArray(msg)) {
        message = msg.join('; ');
      } else {
        message = msg as string;
      }
    } else {
      message = getCodeMessage(responseCode);
    }

    // 创建错误响应
    const errorResponse = createErrorResponse(responseCode, message, request.url);

    // 记录错误日志
    this.logger.error(
      `HTTP Exception: ${status} - ${message} - ${request.method} ${request.url}`,
      exception.stack,
    );

    // 返回错误响应
    response.status(HttpStatus.OK).send(errorResponse);
  }
}

/**
 * 全局异常过滤器
 * 捕获所有未处理的异常
 */
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<FastifyReply>();
    const request = ctx.getRequest<FastifyRequest>();

    // 获取错误信息
    let message = '服务器内部错误';
    let responseCode = ResponseCode.INTERNAL_SERVER_ERROR;

    if (exception instanceof Error) {
      message = exception.message;
      // 根据错误类型设置不同的状态码
      if (exception.name === 'ValidationError') {
        responseCode = ResponseCode.VALIDATION_ERROR;
      } else if (exception.name === 'TypeError') {
        responseCode = ResponseCode.BAD_REQUEST;
      }
    }

    // 创建错误响应
    const errorResponse = createErrorResponse(responseCode, message, request.url);

    // 记录错误日志
    this.logger.error(
      `Unhandled Exception: ${message} - ${request.method} ${request.url}`,
      exception instanceof Error ? exception.stack : String(exception),
    );

    // 返回错误响应
    response.status(HttpStatus.OK).send(errorResponse);
  }
} 